import React, { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { translateDataField } from '../../../utils/i18nDataTranslator';
import {
  Table,
  Button,
  Space,
  Input,
  message,
  Card,
  Pagination,
  Row,
  Col
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  SearchOutlined
} from '@ant-design/icons';

interface DepartmentItem {
  id: number;
  name: string;
  manager: string;
  phone: string;
  gender: 'male' | 'female';
}

interface FormValues {
  name: string;
  manager: string;
  phone: string;
  gender: 'male' | 'female';
}


interface ErrorResponse {
  error: string;
}

const MarketingManagement: React.FC = () => {
  const { t } = useTranslation('marketing');
  const [data, setData] = useState<DepartmentItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingItem, setEditingItem] = useState<DepartmentItem | null>(null);
  const [searchKeyword, setSearchKeyword] = useState('');
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });

  // 使用原生表单状态管理
  const [formData, setFormData] = useState<FormValues>({
    name: '',
    manager: '',
    phone: '',
    gender: 'male'
  });

  //修改 fetchData 函数
  const fetchData = async () => {
    setLoading(true);
    try {
      const apiUrl = `http://localhost:3001/api/marketing?page=${pagination.current}&pageSize=${pagination.pageSize}&keyword=${searchKeyword}`;

      console.log('正在请求:', apiUrl);

      const response = await fetch(apiUrl);

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const result = await response.json();

      console.log('获取数据成功:', result);

      // 添加空值检查和安全处理
      const dataArray = Array.isArray(result) ? result : (result.data || []);
      setData(dataArray);

      // 安全处理分页数据
      if (result.pagination) {
        setPagination(prev => ({
          ...prev,
          total: result.pagination.total || dataArray.length
        }));
      } else {
        // 如果没有分页信息，使用默认值
        setPagination(prev => ({
          ...prev,
          total: dataArray.length
        }));
      }
    } catch (error) {
      console.error('获取数据失败:', error);
      message.error('获取数据失败');
      // 确保在错误情况下设置空数组
      setData([]);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchData();
  }, [pagination.current, pagination.pageSize, searchKeyword]);

  // 处理搜索
  const handleSearch = (value: string) => {
    setSearchKeyword(value);
    setPagination(prev => ({ ...prev, current: 1 }));
  };

  // 打开新增模态框
  const handleAdd = () => {
    setEditingItem(null);
    setFormData({
      name: '',
      manager: '',
      phone: '',
      gender: 'male'
    });
    setModalVisible(true);
  };

  // 打开编辑模态框
  const handleEdit = (record: DepartmentItem) => {
    setEditingItem(record);
    setFormData({
      name: record.name,
      manager: record.manager,
      phone: record.phone,
      gender: record.gender
    });
    setModalVisible(true);
  };

  // 处理删除 - 使用原生确认对话框
  const handleDelete = async (id: number, name: string) => {
    // 使用原生 confirm 对话框
    const isConfirmed = window.confirm(`${t('confirmDelete')} "${name}" 吗？`);

    if (!isConfirmed) {
      return; // 用户取消删除
    }

    try {
      const response = await fetch(`http://localhost:3001/api/marketing/${id}`, {
        method: 'DELETE'
      });

      if (response.ok) {
        message.success(t('deleteSuccess'));
        fetchData();
      } else {
        const errorData: ErrorResponse = await response.json();
        message.error(errorData.error || t('deleteFailed'));
      }
    } catch (error) {
      console.error('删除失败:', error);
      message.error(t('deleteFailed'));
    }
  };

  // 处理表单字段变化
  const handleInputChange = (field: keyof FormValues, value: string) => {
    setFormData(prev => ({
      ...prev,
      [field]: value
    }));
  };

  // 处理表单提交
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    // 简单验证
    if (!formData.name.trim()) {
      message.error(t('pleaseInputDepartmentName'));
      return;
    }
    if (!formData.manager.trim()) {
      message.error(t('pleaseInputManager'));
      return;
    }
    if (!formData.phone.trim()) {
      message.error('请输入手机号');
      return;
    }
    if (!/^1[3-9]\d{9}$/.test(formData.phone)) {
      message.error('请输入正确的手机号');
      return;
    }

    try {
      const url = editingItem
        ? `http://localhost:3001/api/marketing/${editingItem.id}`
        : 'http://localhost:3001/api/marketing';
      const method = editingItem ? 'PUT' : 'POST';

      const response = await fetch(url, {
        method,
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(formData)
      });

      if (response.ok) {
        message.success(editingItem ? '更新成功' : '创建成功');
        setModalVisible(false);
        fetchData();
      } else {
        const errorData: ErrorResponse = await response.json();
        message.error(errorData.error || t('operationFailed'));
      }
    } catch (error) {
      console.error('操作失败:', error);
      message.error(t('operationFailed'));
    }
  };

  // 关闭模态框
  const handleCloseModal = () => {
    setModalVisible(false);
  };

  // 表格列定义
  const columns = [
    {
      title: t('departmentName'),
      dataIndex: 'name',
      key: 'name',
      width: 200
    },
    {
      title: t('manager'),
      dataIndex: 'manager',
      key: 'manager',
      width: 120
    },
    {
      title: t('phone'),
      dataIndex: 'phone',
      key: 'phone',
      width: 130
    },
    {
      title: t('gender'),
      dataIndex: 'gender',
      key: 'gender',
      width: 80,
      render: (gender: string) => translateDataField(gender, 'gender', t, 'marketing')
    },
    {
      title: t('operation'),
      key: 'action',
      width: 120,
      render: (_: unknown, record: DepartmentItem) => (
        <Space size="small">
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            {t('common:edit')}
          </Button>
          <Button
            type="link"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record.id, record.name)}
          >
            {t('common:delete')}
          </Button>
        </Space>
      )
    }
  ];

  // 模态框样式
  const modalStyle: React.CSSProperties = {
    position: 'fixed',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    backgroundColor: 'rgba(0, 0, 0, 0.5)',
    display: modalVisible ? 'flex' : 'none',
    justifyContent: 'center',
    alignItems: 'center',
    zIndex: 1000
  };

  const modalContentStyle: React.CSSProperties = {
    backgroundColor: 'white',
    padding: '24px',
    borderRadius: '8px',
    width: '500px',
    maxWidth: '90vw',
    boxShadow: '0 4px 6px rgba(0, 0, 0, 0.1)'
  };

  const formItemStyle: React.CSSProperties = {
    marginBottom: '16px'
  };

  const labelStyle: React.CSSProperties = {
    display: 'block',
    marginBottom: '4px',
    fontWeight: 'bold'
  };

  const inputStyle: React.CSSProperties = {
    width: '100%',
    padding: '8px 12px',
    border: '1px solid #d9d9d9',
    borderRadius: '6px',
    fontSize: '14px'
  };

  const selectStyle: React.CSSProperties = {
    ...inputStyle,
    backgroundColor: 'white'
  };

  return (
    <div style={{ padding: 24 }}>
      <Card>
        {/* 搜索和操作栏 */}
        <Row justify="space-between" style={{ marginBottom: 16 }}>
          <Col>
            <Input.Search
              placeholder={t('searchPlaceholder')}
              allowClear
              style={{ width: 300 }}
              onSearch={handleSearch}
              enterButton={<SearchOutlined />}
            />
          </Col>
          <Col>
            <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
              {t('addDepartment')}
            </Button>
          </Col>
        </Row>

        {/* 数据表格 */}
        <Table
          columns={columns}
          dataSource={data}
          rowKey="id"
          loading={loading}
          pagination={false}
          scroll={{ x: 800 }}
        />

        {/* 分页 */}
        <div style={{ marginTop: 16, textAlign: 'right' }}>
          <Pagination
            current={pagination.current}
            pageSize={pagination.pageSize}
            total={pagination.total || 0}  // 添加安全处理
            showSizeChanger
            showQuickJumper
            showTotal={(total, range) =>
              `${t('paginationTotal')} ${range[0]}${t('paginationRange')}${range[1]} ${t('paginationOf')} ${total} ${t('paginationRecords')}`
            }
            onChange={(page, pageSize) => {
              setPagination(prev => ({
                ...prev,
                current: page,
                pageSize: pageSize || prev.pageSize
              }));
            }}
          />
        </div>
      </Card>

      {/* 原生 HTML 模态框和表单 */}
      <div style={modalStyle} onClick={handleCloseModal}>
        <div style={modalContentStyle} onClick={(e) => e.stopPropagation()}>
          <h2 style={{ marginBottom: '20px', marginTop: 0 }}>
            {editingItem ? t('editDepartment') : t('addDepartment')}
          </h2>

          <form onSubmit={handleSubmit}>
            <div style={formItemStyle}>
              <label style={labelStyle}>{t('departmentName')}</label>
              <input
                type="text"
                style={inputStyle}
                placeholder={t('pleaseInput') + t('departmentName')}
                value={formData.name}
                onChange={(e) => handleInputChange('name', e.target.value)}
              />
            </div>

            <div style={formItemStyle}>
              <label style={labelStyle}>{t('manager')}</label>
              <input
                type="text"
                style={inputStyle}
                placeholder={t('pleaseInput') + t('manager')}
                value={formData.manager}
                onChange={(e) => handleInputChange('manager', e.target.value)}
              />
            </div>

            <div style={formItemStyle}>
              <label style={labelStyle}>{t('phone')}</label>
              <input
                type="text"
                style={inputStyle}
                placeholder={t('pleaseInput') + t('phone')}
                value={formData.phone}
                onChange={(e) => handleInputChange('phone', e.target.value)}
              />
            </div>

            <div style={formItemStyle}>
              <label style={labelStyle}>{t('gender')}</label>
              <select
                style={selectStyle}
                value={formData.gender}
                onChange={(e) => handleInputChange('gender', e.target.value)}
              >
                <option value="male">{t('male')}</option>
                <option value="female">{t('female')}</option>
              </select>
            </div>

            <div style={{ textAlign: 'right', marginTop: '20px' }}>
              <Space>
                <Button onClick={handleCloseModal}>
                  {t('cancel')}
                </Button>
                <Button type="primary" htmlType="submit">
                  {editingItem ? t('update') : t('create')}
                </Button>
              </Space>
            </div>
          </form>
        </div>
      </div>
    </div>
  );
};

export default MarketingManagement;